package com.stylefeng.guns.modular.flagglory.controller;

import com.stylefeng.guns.common.persistence.model.Book;
import com.stylefeng.guns.core.base.controller.BaseController;
import com.stylefeng.guns.core.log.LogObjectHolder;
import com.stylefeng.guns.modular.flagglory.service.IBookService;
import com.stylefeng.guns.modular.flagglory.service.IChapterService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.validation.Valid;

/**
 * 学习园地控制器
 *
 * @author fengshuonan
 * @Date 2018-02-05 08:53:20
 */
@Controller
@RequestMapping("/book")
public class BookController extends BaseController {

    private String PREFIX = "/flagGlory/book/";

    @Autowired
    private IBookService bookService;
    @Autowired
    private IChapterService chapterService;

    /**
     * 跳转到学习园地首页
     */
    @RequestMapping("")
    public String index() {
        return PREFIX + "book.html";
    }

    /**
     * 跳转到添加学习园地
     */
    @RequestMapping("/book_add")
    public String bookAdd() {
        return PREFIX + "book_add.html";
    }

    /**
     * 跳转到修改学习园地
     */
    @RequestMapping("/book_update/{bookId}")
    public String bookUpdate(@PathVariable Integer bookId, Model model) {
        Book book = bookService.selectById(bookId);
        model.addAttribute("item", book);
        LogObjectHolder.me().set(book);
        return PREFIX + "book_edit.html";
    }

    /**
     * 获取学习园地列表
     */
    @RequestMapping(value = "/list")
    @ResponseBody
    public Object list(String condition) {
        return bookService.selectList(null);
    }

    /**
     * 新增学习园地
     */
    @RequestMapping(value = "/add")
    @ResponseBody
    public Object add(@Valid Book book, BindingResult result) throws Exception {
        if (result.hasErrors()) {
            throw new Exception(result.getFieldError().getDefaultMessage());
        }
        bookService.insert(book);
        return super.SUCCESS_TIP;
    }

    /**
     * 删除学习园地
     */
    @RequestMapping(value = "/delete")
    @ResponseBody
    public Object delete(@RequestParam Integer bookId) {
        bookService.deleteById(bookId);
        return SUCCESS_TIP;
    }

    /**
     * 修改学习园地
     */
    @RequestMapping(value = "/update")
    @ResponseBody
    public Object update(@Valid Book book, BindingResult result) throws Exception {
        if (result.hasErrors()) {
            throw new Exception(result.getFieldError().getDefaultMessage());
        }
        bookService.updateById(book);
        return super.SUCCESS_TIP;
    }
}
